<template>
<div>
  <div id="containerPhoto" style="width: 100%; height: 810px"></div>
<div>1323</div>
</div>
</template>

<script>
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import '../../utils/LeafletPlayback'
import '@/utils/map.js'
// 路线规划
import 'leaflet-routing-machine/dist/leaflet-routing-machine.css';
import 'leaflet-routing-machine';


import GPS from '../../utils/GPS.js'
import { getMapDataApi } from '@/api/proofOnly/index'
import 'leaflet.markercluster/dist/MarkerCluster.css';
import 'leaflet.markercluster/dist/MarkerCluster.Default.css';
import 'leaflet.markercluster/dist/leaflet.markercluster';
import 'leaflet-routing-machine/dist/leaflet-routing-machine.css';
import 'leaflet-routing-machine/dist/leaflet-routing-machine.js';
import 'leaflet-control-geocoder/dist/Control.Geocoder.css';
import 'leaflet-control-geocoder/dist/Control.Geocoder.js';
import { parseTime } from '@/utils/index'
export default {
  name: "",
  props:['value1'],
  data() {
    return {
      positionList:[],
      map:null,
      globalMarkersLayerGroup: ''
    };
  },
  mounted() {
    this.initMap();
  },
  watch: {
    value1: function (newVal, oldVal) {

      this.initMapData();
    },
  },
  created() {
    // this.initMap()
    this.initMapData();
  },
  methods: {
    formateDate(date){
      return parseTime(date)
    },
    initMapData(){

      let data = {
        proof_num:this.value1
      };
      getMapDataApi(data).then(res=>{
        console.log(res.data);
        this.positionList = res.data;
        this.addMarker()
      }).catch(err=>{

      })
    },
    
    addMarker(map) {
      let that=this;


    //设置图标样式
      var myIcon = L.icon({
        iconUrl: require('../../assets/po.png'),
        iconSize: [30, 30],
        iconAnchor: [16, 28],
        popupAnchor: [-3, -76],
        shadowUrl: 'my-icon-shadow.png',
      
      });

    const markersList = L.markerClusterGroup();

    // 清除之前的标记
    if (this.globalMarkersLayerGroup) {
        this.globalMarkersLayerGroup.clearLayers();
    }
    var polylines = [];
    let currentRoute; // 保持对当前路线的引用
  let lastClickedPoint = null; // 保持对上一次点击的路径点的引用
    // 创建一些标记并添加到标记集群
    for (let i = 0; i < this.positionList.length; i++) {
      const element = this.positionList[i];

      if(element.data_type == 0 || element.data_type == 1){
        const marker = L.marker([element.Latitude, element.Longitude], { icon: myIcon }).bindPopup(generatePopupContent(element));
          marker.on('click', () => {
            // 在这里可以自定义点击 marker 后的操作
            marker.openPopup();
            if (lastClickedPoint && lastClickedPoint === element) {
              return;
            }

            
            if(element.data_type == 1){
              // startMapLine(element.Latitude, element.Longitude, element.Latitude_end, element.Longitude_end)
              
              // 如果当前路线存在，则删除它
              if (currentRoute) {
                that.map.removeLayer(currentRoute);
              }
                  // 在弹窗打开时绘制新路线
              currentRoute = startMapLine(element.Latitude, element.Longitude, element.Latitude_end, element.Longitude_end);
              that.map.addLayer(currentRoute);

              // 更新上一次点击的路径点
              lastClickedPoint = element;
              startMapLine(element.Latitude, element.Longitude,element.Latitude_end, element.Longitude_end)
            }
          });
          markersList.addLayer(marker);
          let that = this;
          // 添加一个函数用于生成弹窗内容
          function generatePopupContent(element) {
            let content = '';

            if (element.data_type === 0 && element.path !== '') {
              content = `<div style="font-size:13px;"><b>文件名：${element.title}</b><br>文件路径：${element.path}<br>时间：${initDate(element.infoTime)}<br>
              <img src=${$IP+element.path} width="200" height="200" /></div>
              `;
            } else if (element.data_type === 0 && element.path === '') {
              content = `<div style="font-size:13px;"><b>地点：${element.title}</b><br>时间：${initDate(element.infoTime)}</div>`;
            }else if(element.data_type == 1){
              content = `<div style="font-size:13px;"><b>地点：${element.title}</b><br>时间：${initDate(element.infoTime)}<br>路线数据</div>`;
              
            }
            // 添加其他条件分支或内容生成逻辑
            return content;
          }

          function initDate(time,cFormat){
            if (arguments.length === 0 || !time) {
                  return '暂无时间信息'
                }
                const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
                let date
                if (typeof time === 'object') {
                  date = time
                } else {
                  if ((typeof time === 'string')) {
                    if ((/^[0-9]+$/.test(time))) {
                      // support "1548221490638"
                      time = parseInt(time);
                    } else {
                      // support safari
                      // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
                      time = time.replace(new RegExp(/-/gm), '/');
                    }
                  }

                  if ((typeof time === 'number') && (time.toString().length === 10)) {
                    time = time * 1000
                  }
                  date = new Date(time)
                }
                const formatObj = {
                  y: date.getFullYear(),
                  m: date.getMonth() + 1,
                  d: date.getDate(),
                  h: date.getHours(),
                  i: date.getMinutes(),
                  s: date.getSeconds(),
                  a: date.getDay()
                }
                const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
                  const value = formatObj[key]
                  // Note: getDay() returns 0 on Sunday
                  if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
                  return value.toString().padStart(2, '0');
                })
                return time_str
          }
          function startMapLine(start1, start2, end1, end2){
                var control = L.Routing.control({
                  waypoints: [
                    L.latLng([start1, start2]),
                    L.latLng([end1, end2]),
                  ],
                  routeWhileDragging: false,
                  lineOptions: {
                    styles: [{ color: 'red', opacity: 1, weight: 5 }],
                  },
                  createMarker: function (i, waypoint, n) {
                  var markerIcon = L.icon({
                    iconUrl: i === 0 ? require('../../assets/start.png') : require('../../assets/end.png'),
                    iconSize: [30, 30],
                    iconAnchor: [16, 28],
                    popupAnchor: [-3, -76],
                  });

                  var marker = L.marker(waypoint.latLng, { icon: markerIcon });

                  marker.bindPopup(`<b>地点：${element.title}</b><br>时间：${initDate(element.infoTime)}<br>路线数据`);

                  return marker;
                },
                show: false,
                }).addTo(that.map);

              }

      }else{
        polylines.push(element)
      }
    }
    // 将标记集群添加到地图
    this.map.addLayer(markersList);
// 更新全局标记图层组的引用
this.globalMarkersLayerGroup = markersList;

    return

    },
    initMap() {
      

      let map = L.map("containerPhoto", {
                // minZoom: 10,
                // maxZoom: 15,
                center: [38.04,114.51],
                zoom: 5,
                zoomDelta: 0.5,
                fullscreenControl: true,
                zoomControl: false,
                attributionControl: false
      });
      this.map = map;

      
      //http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}//arcgis在线地图
      this.baseLayer = L.tileLayer(
        "http://rt0.map.gtimg.com/realtimerender?z={z}&x={x}&y={-y}&type=vector&style=0",
        {
          attribution: "© 高德地图",
          maxZoom: 15,
          minZoom: 3,
          subdomains: "1234",
          continuousWorld: true, // 避免在地图边界处出现白边
          bounds: [[-85.05112878, -180], [85.05112878, 180]] // 避免在地图边界处出现白边
        }
      );
      this.map.addLayer(this.baseLayer);

    this.addMarker(this.map);
    
    let trajectoryData= [

      [38.00836826287429,114.65955631758962],
      [38.00847000810185,114.65628669726978],
      [38.00959156907704,114.6490372509619],
      [38.00934100467651,114.63783001236891],
      [38.00897389954178,114.62069475333833],
      [38.00866467393563,114.60939904934486],
      [38.00856942280871,114.59365639638419],
      [38.01127658497049,114.57799416032586],
      [38.010986067391364,114.56306598321824],
      [38.010845364559664,114.54704243167569],
      [38.01031183315671,	114.52386899138955],
      [38.01022245367617,114.50110261692198],
      [38.009888762324124,114.48707322335964],
      [38.04351803451472,114.50153283931023],
      [38.027834701425284,114.47737238142038]
    ]

    // 添加图标到指定位置
    var icon = L.icon({
      iconUrl: '../../assets/push.png',
      iconSize: [20, 20], // 图标大小
      iconAnchor: [16, 16], // 图标锚点
    });
   

    var currentIndex = 1;
    },

    
  },
};
</script>

<style>
</style>